﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.customer.dao.impl;

import java.util.*;

import com.hh.bss.auth.entity.SystemUser;
import com.hh.bss.auth.util.AuthSqlUtil;
import com.hh.bss.base.*;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.customer.dao.*;
import com.hh.bss.customer.entity.*;
import com.hh.bss.customer.service.*;
import com.hh.bss.customer.vo.query.*;
import com.hh.bss.util.*;



import static com.hh.bss.util.ObjectUtils.*;

import org.springframework.stereotype.Repository;

@Repository
public class CustomerContractAttachmentDaoImpl extends BaseHibernateDao<CustomerContractAttachment, java.lang.Integer> implements CustomerContractAttachmentDao<CustomerContractAttachment, java.lang.Integer> {

	public Class getEntityClass() {
		return CustomerContractAttachment.class;
	}

	public Page findPage(CustomerContractAttachmentQuery query) {
		// XsqlBuilder syntax,please see
		// http://code.google.com/p/rapid-xsqlbuilder
		// [column]为字符串拼接, {column}为使用占位符.
		// [column]为使用字符串拼接,如username='[username]',偷懒时可以使用字符串拼接
		// [column] 为PageRequest的属性

		Class[] os = { CustomerContractAttachmentQuery.class };
		Class property = org.springframework.beans.BeanUtils.findPropertyType(query.getField_type(), os);
		if (property != null) {
			if ("java.lang.String".equals(property.getName())) {

				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), query.getQuery());

			} else if ("java.lang.Integer".equals(property.getName())) {

				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), StringHelper.parseInteger(query.getQuery(), 0));

			} else if ("java.lang.Double".equals(property.getName())) {
				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), StringHelper.parseDouble(query.getQuery(), 0));
			} else if ("java.util.Date".equals(property.getName())) {
				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), DateHelper.toDate(query.getQuery(), DateHelper.DEFAULT_DATE_FORMAT));
			}
		}
		List values = new ArrayList();
		// 生成sql2的原因是为了不喜欢使用xsqlbuilder的同学，请修改生成器模板，删除本段的生成
		StringBuffer sql = new StringBuffer();
		sql.append(" select * from ( ");
		sql.append("select t.id,t.contract_id contractId,t.attachment_name attachmentName,t.attachment_file attachmentFile,t.attachment_filesize attachmentFilesize,t.attachment_filetype attachmentFiletype,t.upload_dt uploadDt from customer_contract_attachment t where 1=1 ");
		sql.append(" ) tt where 1=1 ");
		if (isNotEmpty(query.getId())) {
			sql.append(" and  tt.id = ? ");
			values.add(query.getId());
		}
		if (isNotEmpty(query.getContractId())) {
			sql.append(" and   tt.contractId = ? ");
			values.add(query.getContractId());
		}
	
		/*
		 * 增加权限控制
		 */
		//query.setOnlineUser(onlineUser);
		if (query.getOnlineUser() != null) {
			String authsql = authSQL(query.getOnlineUser().getUsername(), "tt.contractId");
			if (!StringHelper.isEmpty(authsql)) {
				sql.append(authsql);
			}

		}else{
			log.info("当前用户获取不到.");
		}
		sql.append(" order by tt.uploadDt desc ");
		log.info("合同附件的SQL:" + sql.toString());
		return super.getJdbcDao().createPage(sql.toString(), values.toArray(), new MapObjectRowMapper(), query.getPageSize(), query.getPageNumber());
	}

	private String authSQL(String username, String creatorColumn) {
		// admin不受控制
		if (ConstantDic.ADMIN_USER.equals(username))
			return "";

		SystemUser systemUser = SystemUserCache.getSystemUserByUsername(username);

		StringBuffer sb = new StringBuffer();

		// Account 角色 看全部
		if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_ACCOUNT)) {
			return "";
		}
		// GM 看全部
		if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_GM)) {
			return "";
		}

		if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_SUPER_USER)) {
			return "";
		}

		// Contractor看全部
		if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_CONTRACTOR))
			return "";

		sb.append(" and (");
		// BM可以查看自己区域的 ROLE_Branch_Manager
		if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_Branch_Manager)) {

//			sb.append("  exists ( select 1 from customer_contract_staff t2 where t2.role='BDM' and  t2.contract_id=").append(creatorColumn);
//			sb.append(" and t2.account in (select b.account from system_user b where b.branch_company_id = ");
//			sb.append(" (select ss1.branch_company_id from system_user ss1 where ss1.account='");
//			sb.append(username).append("')))");
			
			sb.append("  exists ( select 1 from customer_contract_staff t2 where t2.role='BDM' and  t2.contract_id=").append(creatorColumn);
			sb.append(" and t2.account in ( ").append(AuthSqlUtil.getSameBranchCompanyStaffSql(username)).append(" ))");
			
			
		} else if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_Manager)) {
			// 包括组内合同的所有附件详情。
			
//			sb.append("  exists ( select 1 from customer_contract_staff t2  where  t2.contract_id=").append(creatorColumn);
//			sb.append("  and t2.account in ");
//			sb.append(" (select b.account from system_user b where b.dept_id = ");
//			sb.append(" (select ss1.dept_id from system_user ss1 where ss1.account='");
//			sb.append(username).append("')))");
						
			sb.append("  exists ( select 1 from customer_contract_staff t2  where  t2.contract_id=").append(creatorColumn);
			sb.append("  and t2.account in ");
			sb.append(" ( ").append(AuthSqlUtil.getSameBranchCompanyStaffSql(username)).append("  ))");
			

		} else if (SystemUserCache.isRole(systemUser.getId(), ConstantDic.ROLE_Consultant)) {
			// 能看到自己参与的合同附件
			log.info("Consultant");
			sb.append("  exists ( select 1 from customer_contract_staff t2  where  t2.contract_id=").append(creatorColumn);
			sb.append("  and t2.account ='");
			sb.append(username).append("')");
		}

		sb.append(" )");

		return sb.toString();

	}

}
